<html>
  <head>
    <style>
      body {
        margin: 0;
        background: #2d2c2f;
        color: #ffffff;
      }
      .navbar {
        font-family: sans-serif;
        border-bottom: 1px solid #1413158c;
        display: flex;
        flex-direction: row;
      }
      .error {
        color: #ff3f3f;
        background: #3e1f1f;
        border-bottom: 1px solid #1413158c;
        display: none;
        padding: 10px;
        margin: 0;
      }
      input {
        background: transparent;
        color: white;
        border: none;
        border: 1px solid #4f475a;
        border-radius: 3px;
        padding: 5px;
        margin: 5px;
      }
      .title {
        flex: 2;
      }
      .url {
        flex: 5;
      }
      .rate {
        flex: 1;
      }
    </style>
  </head>
  <body>
    <div class="navbar">
      <input
        type="text"
        class="title"
        title="title of the remote page"
        readonly
      />
      <input type="text" class="url" title="url of the remote page" readonly />
      <input
        type="number"
        class="rate"
        value="0.5"
        min="0"
        step="0.1"
        title="refresh rate (second)"
      />
    </div>
    <pre class="error"></pre>
    <img class="screen" />
  </body>
  <script>
    const id = location.pathname.split('/').slice(-1)[0]
    const elImg = document.querySelector('.screen')
    const elTitle = document.querySelector('.title')
    const elUrl = document.querySelector('.url')
    const elRate = document.querySelector('.rate')
    const elErr = document.querySelector('.error')

    document.title = `Rod Monitor - ${id}`

    async function update() {
      const res = await fetch(`/api/page/${id}`)
      const info = await res.json()
      elTitle.value = info.title
      elUrl.value = info.url

      await new Promise((resolve, reject) => {
        const now = new Date()
        elImg.src = `/screenshot/${id}?t=${now.getTime()}`
        elImg.style.maxWidth = innerWidth + 'px'
        elImg.onload = resolve
        elImg.onerror = () => reject(new Error('error loading screenshots'))
      })
    }

    async function mainLoop() {
      try {
        await update()
        elErr.attributeStyleMap.delete('display')
      } catch (err) {
        elErr.style.display = 'block'
        elErr.textContent = err + ''
      }

      setTimeout(mainLoop, parseFloat(elRate.value) * 1000)
    }

    mainLoop()
  </script>
</html>
